package com.heisenhub.common.oauth.config;

import com.heisenhub.common.oauth.enums.RESTAPI;
import com.heisenhub.common.oauth.hander.ApiResourceOpenHander;
import com.heisenhub.common.oauth.hander.XmAccessDeniedHandler;
import com.heisenhub.common.oauth.hander.XmAuthExceptionEntryPoint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;

/**
 * @author sen
 * @description 资源服务器
 * @date 2024/3/22 10:01
 */
@Configuration
@EnableResourceServer
public class ServerResourceServerConfigure  extends ResourceServerConfigurerAdapter {

    @Autowired
    private XmAccessDeniedHandler accessDeniedHandler;
    @Autowired
    private XmAuthExceptionEntryPoint exceptionEntryPoint;

    @Autowired
    private ApiResourceOpenHander apiResourceOpen;

    @Autowired
    private ApplicationContext applicationContext;

    @Override
    public void configure(HttpSecurity http) throws Exception {

        http.csrf().disable()
                .requestMatchers().antMatchers("/**")
                .and()
                .authorizeRequests()
                .antMatchers(apiResourceOpen.handle(applicationContext, RESTAPI.OPEN)).permitAll() // 放行路径
                .antMatchers(apiResourceOpen.handle(applicationContext, RESTAPI.INTERIOR)).permitAll() // 放行路径
                .antMatchers("/**").authenticated();
    }


    /**
     *  异常翻译
     * @param resources
     */
    @Override
    public void configure(ResourceServerSecurityConfigurer resources) {


        resources.authenticationEntryPoint(exceptionEntryPoint)
                .accessDeniedHandler(accessDeniedHandler);
    }
}
